package com.wt.demo;

/**
 * public void interrupt()  中断线程
 * public boolean isInterrupted()  判断是否被中断
 * public static boolean interrupted() 判断是否被中断，并清除当前中断状态
 * @author: wangtao
 * @date:17:51 2019/6/10
 * @email:386427665@qq.com
 */
public class ThreadSleepInterrupt {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                while (true){
                    if(Thread.currentThread().isInterrupted()){
                        System.out.println("isInterrupted");
                        break;
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        System.out.println("interrupt Exception");
                        // 重新设置中断状态，sleep由于终端而抛出异常，此时他会清除中断状态，
                        // 如果不加处理，在下次循环开始的时候就会无法捕捉这个中断，故在异常处理中，再次设置中断状态
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("aaaaa");
                    Thread.yield();
                }
            }
        };
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
    }
}
